package com.jcfk.system.service;

import com.jcfk.common.core.utils.IdUtils;
import com.jcfk.system.domain.po.SysPortalContentCatalog;
import com.jcfk.system.domain.query.SysPortalContentCatalogQuery;
import com.jcfk.system.domain.dto.SysPortalContentCatalogDTO;
import com.jcfk.system.dao.SysPortalContentCatalogDao;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.web.domain.DataPage;
import com.jcfk.common.web.domain.RetResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;
import com.jcfk.common.core.utils.BeanUtils;
import cn.hutool.core.util.StrUtil;
import com.jcfk.common.security.utils.SecurityUtils;
import com.alibaba.druid.util.StringUtils;

import java.util.*;

import static com.jcfk.common.core.utils.BeanUtils.convertList;

/**
 * 门户内容目录
 *
 * @author awei
 * @email 522891237@gqq.com
 * @date 2024-03-25
 */
@Service
public class SysPortalContentCatalogService extends BaseService<SysPortalContentCatalogDao,SysPortalContentCatalog> {

    /**
     * 根据条件获取单表信息列表
     *
     * @param query 查询条件
     * @return List<SysPortalContentCatalogDTO>
     */
    public List<SysPortalContentCatalogDTO> getList(SysPortalContentCatalogQuery query) {
        // 查询条件
        QueryWrapper<SysPortalContentCatalog> qw = new QueryWrapper<>();
        qw.lambda().likeRight(!StrUtil.isEmpty(query.getCatalogName()), SysPortalContentCatalog::getCatalogName, query.getCatalogName());
        qw.lambda().likeRight( SysPortalContentCatalog::getDeleted, 0);
        // 查询数据
        List<SysPortalContentCatalog> list = super.list(qw);

        return convertList(list, SysPortalContentCatalogDTO.class);
    }

//    Map List MybatisPlus

    /**
     * 根据条件获取门户内容信息树
     *
     * @param query 查询条件
     */
    public List<SysPortalContentCatalogDTO> getTree(SysPortalContentCatalogQuery query) {
        List<SysPortalContentCatalogDTO> tree = new ArrayList<>();
        //获取所有门户目录
        List<SysPortalContentCatalogDTO> allList = this.getList(query);
        //排序
        allList.sort(Comparator.comparing(SysPortalContentCatalogDTO::getSort));

        Map<String, List<SysPortalContentCatalogDTO>> parentChildMap = new HashMap<>();
        // 将节点按照父节点进行分组
        for (SysPortalContentCatalogDTO node : allList) {
            String parentId = node.getParentId();
            parentChildMap.computeIfAbsent(parentId, k -> new ArrayList<>()).add(node);
        }

        // 递归组装树结构
        buildTree(tree, parentChildMap, "0");

        return tree;
    }

    private static void buildTree(List<SysPortalContentCatalogDTO> tree, Map<String, List<SysPortalContentCatalogDTO>> parentChildMap, String parentId) {
        List<SysPortalContentCatalogDTO> children = parentChildMap.get(parentId);
        if (children != null) {
            for (SysPortalContentCatalogDTO child : children) {
                List<SysPortalContentCatalogDTO> grandchildren = parentChildMap.get(child.getId());
                if (grandchildren != null) {
                    buildTree(child.getNodes(), parentChildMap, child.getId());
                }
                tree.add(child);
            }
        }
    }




    /**
     * SysPortalContentCatalog分页查询
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<SysPortalContentCatalogDTO> queryByPage(DataPage<SysPortalContentCatalogDTO> page, SysPortalContentCatalogQuery query) {
        // 分页查询
        query.setCatalogName(StringUtils.isEmpty(query.getCatalogName()) ? query.getCatalogName() : query.getCatalogName() + "%");
        page = this.baseMapper.queryByPage(page, query);
        return page;
    }


        /**
     * 判断SysPortalContentCatalog是已经存在
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(SysPortalContentCatalogDTO dto) {
        QueryWrapper<SysPortalContentCatalog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);
                queryWrapper.eq("version", dto.getVersion());
        if (!StringUtils.isEmpty(dto.getId())) queryWrapper.ne("id", dto.getId());
        Integer count = this.count(queryWrapper);

        if (count > 0) return RetResult.fail("版本号已存在");
                                                                        
        return RetResult.ok();
    }

    /**
     * 插入门户内容目录
     *
     * @param dto 插入对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void insert(SysPortalContentCatalogDTO dto) {

        // 保存
        SysPortalContentCatalog item = new SysPortalContentCatalog();
        BeanUtils.copyProperties(dto, item);
        item.setId(IdUtils.simpleUUID());
        this.setDefaultValue(item);
        this.setAllInfo(item);
        super.save(item);

    }

    /**
     * 更新门户内容目录
     *
     * @param dto 更新对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(SysPortalContentCatalogDTO dto) {

        // 保存
        SysPortalContentCatalog item = new SysPortalContentCatalog();
        BeanUtils.copyProperties(dto, item);

        // 默认数据
        this.setDefaultValue(item);
        this.setAllInfo(item);
        super.updateById(item);
    }

    /**
     * 根据批量主键删除门户内容目录(逻辑删除)
     *
     * @param dto
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean logicDeleteList(SysPortalContentCatalogDTO dto) {

        SysPortalContentCatalog item = new SysPortalContentCatalog();

        this.setDefaultValue(item);
        item.setVersion(dto.getVersion());
        item.setDeleted(1);

        QueryWrapper<SysPortalContentCatalog> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", dto.getIds());

        return this.update(item, queryWrapper);
    }

    /**
     * 设置添加默认值
     *
     * @param item 添加对象
     */
    public void setDefaultValue(SysPortalContentCatalog item) {
        if (StrUtil.isEmpty(item.getCreatedUserId())) {
            item.setCreatedUserId(SecurityUtils.getUserId());
            item.setCreateTime(new Date());
        }
        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdateTime(new Date());
        item.setDeleted(0);

    }

    /**
     * 根据主键获取门户内容目录信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public SysPortalContentCatalogDTO get(String id) {
        // 查询数据
        SysPortalContentCatalog item = this.baseMapper.selectById(id);
            SysPortalContentCatalogDTO dto = new SysPortalContentCatalogDTO();
        try {
            BeanUtils.copyProperties(item, dto);
        } catch (RuntimeException e) {
            throw e;
        }

        return dto;
    }




    public void setAllInfo(SysPortalContentCatalog item) {
        QueryWrapper<SysPortalContentCatalog> qw = new QueryWrapper<>();
        qw.lambda().eq(SysPortalContentCatalog::getId, item.getParentId());

        SysPortalContentCatalog sysPortalContentCatalog = this.baseMapper.selectOne(qw);
        if (sysPortalContentCatalog == null) {
            item.setAllId(item.getId());
            item.setAllCode(item.getCatalogName());
            item.setAllName(item.getCatalogName());
        } else {
            item.setAllId(sysPortalContentCatalog.getAllId() + "," + item.getId());
            item.setAllCode(sysPortalContentCatalog.getAllId() + "," + item.getCatalogName());
            item.setAllName(sysPortalContentCatalog.getAllName() + "," + item.getCatalogName());
        }
    }



}

